package com.mcptt.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;

import com.cloudptt.api.product.log.Log;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.UserInfo;

import java.lang.ref.WeakReference;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private Integer dblock = 0;

    DatabaseHelper(Context context) {
        super(context, DbConst.AUTHORITY, null, DATABASE_VERSION);
        Log.debug(this.getClass(), "DatabaseHelper new ");
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        Log.debug(this.getClass(), "DatabaseHelper onCreate ");
        final int version = db.getVersion();
        Log.debug(this.getClass(), "onCreate version = " + version);

        db.execSQL(DbConst.TABLE_CONFIG_CREATE);
        db.execSQL(DbConst.TABLE_GROUP_CONFIG_CREATE);

        db.execSQL(DbConst.TABLE_GROUP_ADDRESS_CREATE);
        db.execSQL(DbConst.TABLE_MEMBER_ADDRESS_CREATE);

        db.execSQL(DbConst.TABLE_ADDRESS_CREATE);
        db.execSQL(DbConst.TABLE_LOGIN_CREATE);
//        db.execSQL(DbConst.TABLE_MAP_POINT_CREATE);
        db.execSQL(DbConst.VIEW_ADDRESS_CREATE);

        db.execSQL(DbConst.TABLE_HIRSTORY_CREATE);
        db.execSQL(DbConst.TABLE_SESSION_CREATE);
        db.execSQL(DbConst.TABLE_SESSION_GROUP_STATUS_CREATE);
//        insertCRSCTestData(db);//MCS
//        insertTkTestData(db);//TEKE
    }
//    private void insertCRSCTestData(SQLiteDatabase db)//SERVER DIFFERENT
//    {
//        GroupInfo groupInfo = new GroupInfo("5001","group1");
//        insertGroupInfo(db,groupInfo);
//        UserInfo info = new UserInfo("14889399012","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("14889399022","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("14889399032","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("14889399042","5001");
//        insertUserInfo(db,info);
//
//        info = new UserInfo("79110001","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("79110002","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("79110003","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("79110004","5001");
//        insertUserInfo(db,info);
//        info = new UserInfo("79110005","5001");
//        insertUserInfo(db,info);
//    }
//
//    private void insertTkTestData(SQLiteDatabase db)//SERVER DIFFERENT
//    {
//        GroupInfo groupInfo = new GroupInfo("14980025101","group1");
//        insertGroupInfo(db,groupInfo);
//        UserInfo info = new UserInfo("14980024101","14980025101");
//        insertUserInfo(db,info);
//        info = new UserInfo("14980024102","14980025101");
//        insertUserInfo(db,info);
//        info = new UserInfo("14980024103","14980025101");
//        insertUserInfo(db,info);
//        info = new UserInfo("14980024104","14980025101");
//        insertUserInfo(db,info);
//        info = new UserInfo("14980024105","14980025101");
//        insertUserInfo(db,info);
//        info = new UserInfo("14980024106","14980025101");
//        insertUserInfo(db,info);
//    }
//    private void insertGroupInfo(SQLiteDatabase db,GroupInfo info)
//    {
//        StringBuffer strBuf = new StringBuffer();
//        strBuf.append("INSERT INTO ").append(DbConst.Table_GroupAddress).append("(");
//        strBuf.append(DbConst.COL_Type).append(",");
//        strBuf.append(DbConst.COL_AddrId).append(",");
//        strBuf.append(DbConst.COL_Name).append(",");
////        strBuf.append(DbConst.COL_GroupId).append(",");
//        strBuf.append(DbConst.COL_Attr).append(")VALUES (");
//        strBuf.append(info.getType()).append(",");
//        strBuf.append("\"").append(info.getAddrId()).append("\"").append(",");
//        strBuf.append("\"").append(info.getName()).append("\"").append(",");
////        strBuf.append(info.getGroupId()).append(",");
//        strBuf.append(info.getAttr()).append(");");
//        Log.debug(this.getClass(), "insertGroupInfo strBuf.toString() = " + strBuf.toString());
//        db.execSQL(strBuf.toString());
//    }
//
//
//    private void insertUserInfo(SQLiteDatabase db,UserInfo info)
//    {
//        StringBuffer strBuf = new StringBuffer();
//        strBuf.append("INSERT INTO ").append(DbConst.Table_Address).append("(");
//        strBuf.append(DbConst.COL_Type).append(",");
//        strBuf.append(DbConst.COL_AddrId).append(",");
//        strBuf.append(DbConst.COL_Name).append(",");
////        strBuf.append(DbConst.COL_GroupId).append(",");
//        strBuf.append(DbConst.COL_Attr).append(")VALUES (");
//        strBuf.append(info.getType()).append(",");
//        strBuf.append("\"").append(info.getAddrId()).append("\"").append(",");
//        strBuf.append("\"").append(info.getName()).append("\"").append(",");
////        strBuf.append("\"").append(info.getGroupId()).append("\"").append(",");
//        strBuf.append(info.getAttr()).append(");");
//        Log.debug(this.getClass(), "insertUserInfo strBuf.toString() = " + strBuf.toString());
//        db.execSQL(strBuf.toString());
//    }



    public void queryLargeData(String sql, Callback callback) {
        Log.debug(this.getClass(),"queryLargeData sql = " + sql);
        new QueryTask(this,callback).execute(sql);
    }

    private static class QueryTask extends AsyncTask<String, Void, Cursor> {
        private final WeakReference<Callback> callbackWeakRef;
        private DatabaseHelper help = null;

        public QueryTask(DatabaseHelper help,Callback callback) {
            this.help = help;
            this.callbackWeakRef = new WeakReference<>(callback);
        }

        @Override
        protected Cursor doInBackground(String... params) {
            SQLiteDatabase db = help.getReadableDatabase();
            Cursor cursor = db.rawQuery(params[0], null);
            Log.debug(this.getClass(),"doInBackground cursor.getCount() = " + cursor.getCount() + " params[0] = " + params[0]);
            return cursor;
        }

        @Override
        protected void onPostExecute(Cursor cursor) {
            Callback callback = callbackWeakRef.get();
            Log.debug(this.getClass(),"onPostExecute cursor.getCount() = " + cursor.getCount());
            if (callback != null) {
                callback.onDataFetched(cursor);
            }
        }
    }

    public Cursor query(boolean distinct, String table, String[] columns,
                        String selection, String[] selectionArgs, String groupBy,
                        String having, String orderBy, String limit) {
        Cursor cursor = null;
        try {
            SQLiteDatabase db = this.getReadableDatabase();
            cursor = db.query(distinct, table,columns,selection,selectionArgs,groupBy,having,orderBy,limit);
            //如果table不存在，cursor有可能返回null，也有可能返回非null，但调用moveToNext或获取count时会抛出表不存在的错误
            //这里使用下面的方法判断cursor是否有效
            if(cursor.getCount() <= 0){
                cursor = null;
            }
        }catch (Exception e){
            cursor = null;
        }
        return cursor;
    }

    public long insert(String table, String nullColumnHack, ContentValues values)
    {
        synchronized (dblock){
            try {
                SQLiteDatabase db = this.getWritableDatabase();
                return db.insert(table,nullColumnHack,values);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        return -1;
    }

    public long update(String table, ContentValues values,String whereClause, String[] whereArgs)
    {
        synchronized (dblock){
            try {
                SQLiteDatabase db = this.getWritableDatabase();
                return db.update(table,values,whereClause,whereArgs);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        return -1;
    }

    public long delete(String table, String whereClause, String[] whereArgs)
    {
        synchronized (dblock){
            try {
                SQLiteDatabase db = this.getWritableDatabase();
                return db.delete(table,whereClause,whereArgs);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        return -1;
    }

    public void execSQL(String sql) throws SQLException {
        synchronized (dblock){
            try {
                SQLiteDatabase db = this.getWritableDatabase();
                db.execSQL(sql);
            }catch (SQLException e){
                throw e;
            }
        }
    }

    public void execSQL(String sql, Object[] bindArgs) throws SQLException {
        synchronized (dblock){
            try {
                SQLiteDatabase db = this.getWritableDatabase();
                db.execSQL(sql,bindArgs);
            }catch (SQLException e){
                throw e;
            }
        }
    }

    public Cursor rawQuery(String sql, String[] selectionArgs) {
        Cursor cursor = null;
        try {
            SQLiteDatabase db = this.getReadableDatabase();
            cursor = db.rawQuery(sql, selectionArgs);
            //如果table不存在，cursor有可能返回null，也有可能返回非null，但调用moveToNext或获取count时会抛出表不存在的错误
            //这里使用下面的方法判断cursor是否有效
            if(cursor.getCount() <= 0){
                cursor = null;
            }
        }catch (Exception e){
            cursor = null;
        }


        return cursor;
    }

    public boolean checkRecordExists(String tableName, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        try {
            SQLiteDatabase db = this.getReadableDatabase();
            cursor = db.query(tableName, new String[]{"count(*)"}, selection, selectionArgs, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int count = cursor.getInt(0);
                return count > 0;
            }
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return false;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.debug(this.getClass(), "Upgrading database from version "
                + oldVersion + " to " + newVersion);
        //			onCreate(db);
        //	    if(oldVersion < API_VERSION)
        //	    {
        //		Log.debug(this.getClass(), "Upgrading begin");
        //		db.execSQL(TABLE_HIRSTORY_DELETE);
        //		db.execSQL(TABLE_HIRSTORY_CREATE);
        //		db.execSQL(TABLE_SESSION_DELETE);
        //		db.execSQL(TABLE_SESSION_CREATE);
        //		Log.debug(this.getClass(), "Upgrading end");
        //	    }
    }
}
